/*
 * Charger.cpp
 *
 *  Created on: Dec 10, 2011
 *      Author: Michael Anderson
 *      Part of Team 955 Battery Cart project
 *      compiled on Eclipse with Arduino libraries and avr-gcc
 */

#include "Charger.h"

Charger::Charger(Battery &batt, uint8_t pin, EventManager &log) {
    connectedBattery = &batt;
    chargerID = batt.getID(); //A charger will always have the same ID as its connected battery
    chargePin = pin;
    eManager = &log;
    state = CHARGER_IDLE;
}

charger_state Charger::getState() {
    return state;
}

void Charger::run() {
    if (state == CHARGER_CHARGING && getMinutesSince(chargeStartTime, millis()) >= CHARGER_TIMEOUT_MINS)
        disconnect();
}

bool Charger::connect() {
    if (state == CHARGER_IDLE && connectedBattery->getState() == BATTERY_IDLE) {
        state = CHARGER_CHARGING;
        connectedBattery->setState(BATTERY_CHARGING);
        digitalWrite(chargePin, 1);
        chargeStartTime = millis();
        eManager->chargerEvent(chargerID, EVENT_CHARGER_CONNECTED);
        return true;
    }
    return false;
}

bool Charger::disconnect() {
    if (state == CHARGER_IDLE) {
        debugln("Disconnecting charger is idle");
        return false;
    }
    else {
        state = CHARGER_IDLE;
        connectedBattery->setState(BATTERY_IDLE);
        digitalWrite(chargePin, 0);
        eManager->chargerEvent(chargerID, EVENT_CHARGER_DISCONNECTED);
        debugln("Charge successfully cancelled");
        return true;
    }
}
